<?php

namespace app\modules\setting\controllers;

use app\modules\setting\models\RolePermissions;
use app\modules\setting\models\RolesLut;
use app\modules\setting\models\UserPermissions;
use Yii;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\modules\setting\models\User;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;

/**
 * SettingController implements the CRUD actions for SamplePatient model.
 */
class RolePermissionsController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $permission_flags = $this->_get_permission_flags();

        $dataProvider = new ActiveDataProvider([
            'query' => RolesLut::find(),
            'sort' => [
               'defaultOrder' => [
                   'crt_time' => SORT_DESC,
               ]
            ],
        ]);

        return $this->render('roles', [
            'dataProvider' => $dataProvider,
            'permission_flags' => $permission_flags,
        ]);
    }

    public function actionCreate()
    {
        $model = new User();

        if ($model->load(Yii::$app->request->post())) {
            $model->crt_name = Yii::$app->user->identity->username;
            $model->crt_time = date("Y-m-d H:i:s");

            if ($model->checkUsername() && $model->save()) {
                return $this->redirect('/setting/user');
            }
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    public function actionDelete($id)
    {
        $model = User::findOne($id);
        $model->delete();
        
        return $this->redirect('/setting/user');
    }


    /**
     * @param $id
     *
     * @return string|\yii\web\Response
     * @throws \yii\db\Exception
     * @throws \yii\web\NotFoundHttpException
     * @author sally
     * @date   2020-07-06
     */
    public function actionAssignPermissions($id)
    {
        $role_permission = $this->findRolePermissions($id);

        if (Yii::$app->request->post('RolePermissions', false)) {

            $permission_ids = Yii::$app->request->post('RolePermissions');
            $permission_ids = !empty($permission_ids['permission_id']) ? $permission_ids['permission_id'] : [];

            if (RolePermissions::saveRolePermissions($id, $permission_ids)) {
                return $this->redirect(['/setting/role-permissions/']);
            }
        }

        return $this->render('assign-permissions', [
            'model' => $role_permission['model'],
            'role_name' => $role_permission['role_name'],
        ]);
    }


    /**
     * @author sally
     * @date   2020-05-10
     */
    private function _get_permission_flags()
    {
        $is_admin = false;
        $flags = [
            'assign_permission' => false,
        ];
        $permissions = UserPermissions::getPermissions(Yii::$app->user->identity->getId());

        foreach ($permissions as $permission) {
            $flags[$permission['permission_name']] = true;

            if ($permission['permission_name'] == 'full_access') {
                $is_admin = true;
            }
        }

        if ($is_admin) {
            foreach ($flags as $key => $flag) {
                $flags[$key] = true;
            }
        }

        return $flags;
    }


    /**
     * @param $id
     *
     * @return mixed
     * @throws \yii\web\NotFoundHttpException
     * @author sally
     * @date   2020-05-11
     */
    protected function findRolePermissions($id)
    {
        $model = new RolePermissions();

        $permissions = RolePermissions::find()->where(['role_id' => $id, 'delete_at' => 0])->all();
        $permissions = array_column($permissions, 'permission_id');

        $model->role_id = $id;
        $model->permission_id = $permissions;

        if (($role = RolesLut::findOne(['role_id' => $id])) !== null) {
            return [
                'model' => $model,
                'role_name' => $role->description,
            ];
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
